package org.bravo369.inflightxt.services;

import org.bravo369.inflightxt.R;
import org.bravo369.inflightxt.utils.Globals;
import org.bravo369.inflightxt.utils.RunningAverageFilter;

import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;

public class TiltPositionListener implements SensorEventListener {
  private SensorManager sensorManager;
  private TextView pitchView;
  private TextView rollView;
  private TextView headingView;
  private RunningAverageFilter headingFilter;
  private RunningAverageFilter rollFilter;
  private RunningAverageFilter pitchFilter;

  public TiltPositionListener(Activity currentActivity) {
    pitchView = (TextView)currentActivity.findViewById(R.id.txtPitch);
    rollView = (TextView)currentActivity.findViewById(R.id.txtRoll);
    headingView = (TextView)currentActivity.findViewById(R.id.txtHeading);
    headingFilter = new RunningAverageFilter();
    rollFilter = new RunningAverageFilter();
    pitchFilter = new RunningAverageFilter();
    sensorManager = (SensorManager)currentActivity.getSystemService(
        Context.SENSOR_SERVICE);
  }

  public void registerListener() {
    sensorManager.registerListener(
        this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
        SensorManager.SENSOR_DELAY_GAME);
  }

  public void unregisterListener() {
    sensorManager.unregisterListener(this);
  }

  public void exit() {
    unregisterListener();
  }

  @Override
  public void onAccuracyChanged(Sensor arg0, int arg1) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onSensorChanged(SensorEvent event) {
    if (event.accuracy == SensorManager.SENSOR_STATUS_UNRELIABLE)
      return;

    if (event.sensor.getType() != Sensor.TYPE_ORIENTATION)
      return;

    Globals globals = Globals.getInstance();

    float heading = event.values[0];
    float pitch = (event.values[1] + 90.0f) * -1.0f;
    float roll = event.values[2];

    globals.repository.addTiltData(pitch, roll, heading);
    pitchView.setText(Float.toString(pitch));
    rollView.setText(Float.toString(roll));
    headingView.setText(Float.toString(heading));
  }
}
